package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.mapper.ApUserMapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;

import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    ApUserMapper apUserMapper;


    @Override
    public ResponseResult login(LoginDto dto) {

        String phone = dto.getPhone();
        String password = dto.getPassword();
        //1.判断入参是否为空
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)){
            //游客登录

            HashMap<Object, Object> map = new HashMap<>();
            map.put("user",null);
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);

        }
        //正常登录
        LambdaQueryWrapper<ApUser> wrapper=new LambdaQueryWrapper();
        //判断手机是否正确
      wrapper.eq(ApUser::getPhone,phone);
      //获取用户
        ApUser user = apUserMapper.selectOne(wrapper);
        //如果获得的用户名为空，返回错误
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //比对密码
        //获取盐
        String salt = user.getSalt();
        //获取用户密码
        String apUserPassword = user.getPassword();
        //获取加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        //判断用户密码和加密是否匹配
        //不匹配返回错误
        if (!apUserPassword.equals(md5DigestAsHex)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        //返回
        user.setSalt("");
        user.setPassword("");
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);

        //清空敏感资源

        return ResponseResult.okResult(map);
    }
}